/*
 * 9.6
 * Given a matrix in which each row and each column is sorted, write a method to find
 * an element in it.
 *
 */
#include <stdio.h>

/* XXX: failed to solve... */
void search(int **matrix, int row, int col, int x, int *i, int *j)
{
    int r = 0;
    int c = col - 1;
    while (r < row && c >= 0) {
        int v = *((int *)matrix + r*col + c);
        if (v == x) {
            *i = r;
            *j = c;
            return;
        } else if (v > x) {
            c--;
        } else {
            r++;
        }
    }
    *i = -1;
    *j = -1;
}

int main()
{
    int matrix[3][4] = {
        { 0, 1, 3, 6 },
        { 2, 4, 7, 11 },
        { 5, 8, 12, 17 }
    };
    int i, j;
    int d = 7;
    search((int **)matrix, 3, 4, d, &i, &j);
    printf("find %d: [%d,%d]\n", d, i, j);
    d = 16;
    search((int **)matrix, 3, 4, d, &i, &j);
    printf("find %d: [%d,%d]\n", d, i, j);
    return 0;
}

